package com.alipay.rebate.shop.helper;

import com.alibaba.fastjson.JSON;
import com.alipay.rebate.shop.dao.mapper.UserJdPidMapper;
import com.alipay.rebate.shop.model.UserJdPid;
import com.alipay.rebate.shop.pojo.dingdanxia.*;
import com.alipay.rebate.shop.utils.DateUtil;
import com.alipay.rebate.shop.utils.DingdanxiaUtil;
import com.google.common.base.Utf8;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class UserJdPidHelper {

    private Logger logger = LoggerFactory.getLogger(UserIncomeHelper.class);

    Gson gson = new GsonBuilder().create();

    @Resource
    UserJdPidMapper userJdPidMapper;

    public Object getByUnionidPromotionTwo(ByUnionidPromotionTwo req, Long userId) throws IOException {
        logger.debug("getByUnionidPromotionTwo req is : {}",req);
        logger.debug("getByUnionidPromotionTwo userId is : {}",userId);

        //根据用户id查询用户是否存在
        UserJdPid userJdPid1 = userJdPidMapper.selectUserJdPidByUserId(userId);
        logger.debug("selectUserJdPidByUserId is : {}",userJdPid1);

        String materialId = "item.jd.com/"+ req.getMaterialId() +".html";
        req.setMaterialId(materialId);
        logger.debug("materialId is : {}",materialId);

        if (userJdPid1 == null){
            UserJdPid userJdPid = new UserJdPid();
            String spaceNameList = "spaceName";
            DingdanxiaRsp<CreatePositionRsp> createPosition = DingdanxiaUtil.getCreatePosition(spaceNameList);
            CreatePositionRsp data = createPosition.getData();
            logger.debug("CreatePositionRspdate is : {}",data);
            String jsonString = JSON.toJSONString(data);
            logger.debug("jsonString is : {}",jsonString);
            //解析json字符串
            CreatePositionRsp createPositionRsp = gson.fromJson(jsonString, CreatePositionRsp.class);
            logger.debug("createPositionRsp is : {}",createPositionRsp);
            //生成positionId
            req.setPositionId(createPositionRsp.getResultList().getSpaceName());
            logger.debug("req.setPositionId is : {}",req.getPositionId());
            userJdPid.setPositionId(req.getPositionId().toString());
            userJdPid.setUserId(userId);
            userJdPid.setAddTime(new Date());
            userJdPid.setUpdateTime(new Date());
            logger.debug("userJdPid is : {}",userJdPid);
            userJdPidMapper.insert(userJdPid);
        }


        if (userJdPid1 != null){
            logger.debug("userJdPid1.getPositionId() is : {}",userJdPid1.getPositionId());
            if (userJdPid1.getPositionId() == null){
                String spaceNameList = "spaceName";
                DingdanxiaRsp<CreatePositionRsp> createPosition = DingdanxiaUtil.getCreatePosition(spaceNameList);
                CreatePositionRsp data = createPosition.getData();
                logger.debug("CreatePositionRspdate is : {}",data);
                String jsonString = JSON.toJSONString(data);
                logger.debug("jsonString is : {}",jsonString);
                //解析json字符串
                CreatePositionRsp createPositionRsp = gson.fromJson(jsonString, CreatePositionRsp.class);
                logger.debug("createPositionRsp is : {}",createPositionRsp);
                //生成positionId
                Long positionId = createPositionRsp.getResultList().getSpaceName();
                req.setPositionId(positionId);

                userJdPidMapper.updateUserJdPidByUserId(positionId.toString(),userId);

            }else{
                long positionId = Long.valueOf(userJdPid1.getPositionId());
                req.setPositionId(positionId);
            }
        }

        if (req.getCouponUrl() != null) {
            String encode = URLEncoder.encode(req.getCouponUrl(), "utf-8");
            req.setCouponUrl(encode);
        }

        Object byUnionidPromotion = DingdanxiaUtil.getByUnionidPromotionTwo(req);
        logger.debug("byUnionidPromotion is : {}",byUnionidPromotion);

        return byUnionidPromotion;
    }

    public Object getPddConvert(PddConvertReq req,Long userId) throws IOException {

        logger.debug("getPddConvert req is : {}",req);
        logger.debug("getPddConvert userId is : {}",userId);

        //根据用户id查询用户是否存在
        UserJdPid userJdPid1 = userJdPidMapper.selectUserJdPidByUserId(userId);
        logger.debug("selectUserJdPidByUserId is : {}",userJdPid1);

        if (userJdPid1 == null){
            String pIdName = userId + "123";
            List<String> p_id_name_list = new ArrayList<>();
            p_id_name_list.add(pIdName);

            Object pddPidgenerate = DingdanxiaUtil.getPddPidgenerate();

            logger.debug("pddPidgenerate is : {}",pddPidgenerate);
            String jsonString = JSON.toJSONString(pddPidgenerate);
            logger.debug("jsonString is : {}",jsonString);

            String substring = jsonString.substring(jsonString.indexOf("[") + 1, jsonString.lastIndexOf("]"));


            //解析json字符串
            PddPidgenerateRsp pddPidgenerateRsp = gson.fromJson(substring, PddPidgenerateRsp.class);
            logger.debug("pddPidgenerateRsp is : {}",pddPidgenerateRsp);
            //生成positionId
            req.setP_id(pddPidgenerateRsp.getP_id());
            logger.debug("req.setP_id is : {}",req.getP_id());
            UserJdPid userJdPid = new UserJdPid();
            userJdPid.setPddPId(req.getP_id());
            userJdPid.setUserId(userId);
            userJdPid.setAddTime(new Date());
            userJdPid.setUpdateTime(new Date());
            logger.debug("userJdPid is : {}",userJdPid);
            userJdPidMapper.insert(userJdPid);


        }

        if (userJdPid1 != null){
            if (userJdPid1.getPddPId() == null){


                Object pddPidgenerate = DingdanxiaUtil.getPddPidgenerate();

                logger.debug("update is : {}",pddPidgenerate);
                String jsonString = JSON.toJSONString(pddPidgenerate);
                logger.debug("jsonString is : {}",jsonString);

                String substring = jsonString.substring(jsonString.indexOf("[") + 1, jsonString.lastIndexOf("]"));


                //解析json字符串
                PddPidgenerateRsp pddPidgenerateRsp = gson.fromJson(substring, PddPidgenerateRsp.class);
                logger.debug("update is : {}",pddPidgenerateRsp);
                //生成positionId
                String pId = pddPidgenerateRsp.getP_id();
                logger.debug("pid is : {}",pId);
                req.setP_id(pddPidgenerateRsp.getP_id());
                int i = userJdPidMapper.updateUserPddPIdByUserId(pId, userId);
                logger.debug("result i is : {} ",i);

            }else{
                req.setP_id(userJdPid1.getPddPId());
            }
        }

        Object pddConvert = DingdanxiaUtil.getPddConvert(req);

        return pddConvert;
    }


    public String getPddPid(UserJdPid userJdPid,Long userId) throws IOException {

        String pid = null;

        if (userJdPid == null) {
            logger.debug("user is null");
            Object pddPidgenerate = DingdanxiaUtil.getPddPidgenerate();

            logger.debug("pddPidgenerate is : {}", pddPidgenerate);
            String jsonString = JSON.toJSONString(pddPidgenerate);
            logger.debug("jsonString is : {}", jsonString);
            String substring = jsonString.substring(jsonString.indexOf("[") + 1, jsonString.lastIndexOf("]"));
            //解析json字符串
            PddPidgenerateRsp pddPidgenerateRsp = gson.fromJson(substring, PddPidgenerateRsp.class);
            logger.debug("pddPidGenerateRsp is : {}",pddPidgenerateRsp);
            pid = pddPidgenerateRsp.getP_id();
            logger.debug("pid is : {}",pid);
            userJdPid.setPddPId(pid);
            userJdPid.setUserId(userId);
            userJdPid.setAddTime(new Date());
            userJdPid.setUpdateTime(new Date());
            logger.debug("userJdPid is : {}",userJdPid);
            userJdPidMapper.insert(userJdPid);
        }
        if (userJdPid != null){

            logger.debug("user pid is null");
            if (userJdPid.getPddPId() == null){
                Object pddPidgenerate = DingdanxiaUtil.getPddPidgenerate();

                logger.debug("pddPidgenerate is : {}", pddPidgenerate);
                String jsonString = JSON.toJSONString(pddPidgenerate);
                logger.debug("jsonString is : {}", jsonString);
                String substring = jsonString.substring(jsonString.indexOf("[") + 1, jsonString.lastIndexOf("]"));
                //解析json字符串
                PddPidgenerateRsp pddPidgenerateRsp = gson.fromJson(substring, PddPidgenerateRsp.class);
                pid = pddPidgenerateRsp.getP_id();
                userJdPid.setPddPId(pid);
                userJdPid.setUserId(userId);
                userJdPid.setUpdateTime(new Date());
                int i = userJdPidMapper.updateUserPddPIdByUserId(pid, userId);
                logger.debug("result i is : {} ",i);
            }

            if (userJdPid.getPositionId() != null){
                pid = userJdPidMapper.selectUserPddPidByUserId(userId);
                logger.debug("pid is : {}",pid);
            }

        }

        return pid;
    }

}
